package com.fesine.hibernate.service;

import com.fesine.hibernate.model.Class;
import com.fesine.hibernate.model.Student;
import com.fesine.hibernate.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Iterator;
import java.util.Set;

/**
 * Created by Fesine on 2016/5/22.
 */
public class TeacherTest2 {

    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    private Session session;


    @Before
    public void setUp() throws Exception {
        // 4、创建session
        session = sessionFactory.openSession();
        // 5、开启事务
        session.beginTransaction();
    }

    @After
    public void tearDown() throws Exception {
        // 提交事务
        session.getTransaction().commit();
        session.close();
    }

    @Test
    public void testSave() throws Exception {
        Class c = new Class();
        c.setName("03计算机系");
        Student student = new Student();
        student.setName("fesine");
        //student.setC(c);
        Student student1 = new Student();
        student1.setName("soly");
        //student1.setC(c);
        c.getStudents().add(student);
        c.getStudents().add(student1);
        session.save(c);//没有先插入班级信息，而是在插入学生信息时同步完成插入班级信息
        //session.save(student);
        //session.save(student1);
    }


    @Test
    public void listClass() throws Exception {
        Class c = (Class) session.get(Class.class, Long.valueOf(3));
        Set<Student> students = c.getStudents();
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            System.out.println(student);
        }
    }

    @Test
    public void testAdd() throws Exception {
        Class c = new Class();
        c.setName("03计算机系");
        Student student = new Student();
        student.setName("张三");
        //session.save(c);
        session.save(student);
    }

    @Test
    public void testInverse() throws Exception {
        Class c = (Class) session.get(Class.class, Long.valueOf(1));
        Student student = (Student) session.get(Student.class, Long.valueOf(2));
        student.setC(c);
        c.getStudents().add(student);
    }
}
